﻿using IdentityModel.Client;
using Newtonsoft.Json.Linq;
using System;
using System.Net.Http;

namespace ConsoleApp
{
  class Program
  {
    static void Main(string[] args)
    {
      // 从元数据中发现客户端
      var disco = DiscoveryClient.GetAsync("http://localhost:5500").Result;

      // 请求令牌
      var tokenClient = new TokenClient(disco.TokenEndpoint, "roclient", "secret");
      var tokenResponse = tokenClient.RequestResourceOwnerPasswordAsync("jiangy", "1", "api2").Result;//使用用户名密码

      if (tokenResponse.IsError)
      {
        Console.WriteLine(tokenResponse.Error);
        return;
      }

      Console.WriteLine(tokenResponse.Json);

      //访问Api
      var client = new HttpClient();
      //把令牌添加进请求
      client.SetBearerToken(tokenResponse.AccessToken);

      var response = client.GetAsync("http://localhost:5501/api/values").Result;
      if (!response.IsSuccessStatusCode)
      {
        var str = response.Content.ReadAsStringAsync().Result;
        Console.WriteLine("message: " + str);
        Console.WriteLine(response.StatusCode);
      }
      else
      {
        var content = response.Content.ReadAsStringAsync().Result;
        Console.WriteLine(JArray.Parse(content));
      }

      Console.ReadLine();
    }
  }
}
